<?php

namespace App\Console\Commands;

use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use App\Model\Lottery\LotteryHistory;
use App\Model\Lottery\LotteryOrder;
use App\Model\Lottery\LotteryProduct;

class SendLottery extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'lottery:send';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command lottery:send';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        # 先查看这款商品是否存在，是否未开奖，是否过了开奖时间
        $history = LotteryHistory::select('id', 'total', 'sale_total')->where('status', 0)->where('end_time', '<', currentTime())->where('deleted_at', 0)->get();
        if(!$history){
            return ;
        }
        # 循环开奖表
        foreach($history as $item=>$value)
        {
            # 查看开奖的订单是否够数
            $orderCount = LotteryOrder::where('history_id', $value->id)->where('status', 1)->where('deleted_at', 0)->count();
            if($orderCount == $value->total && $value->total == $value->sale_total){
                LotteryProduct::startLottery($value->id);
            }
            else {
                LotteryProduct::cancelLottery($value->id);
            }
        }

    }
}
